<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace app\api\controller\v4;

use app\api\controller\v2\Auth;
use app\common\cachemodel\OrdersLib;
use app\common\lib\astrolog\Acg;
use app\common\lib\exception\ApiException;
use app\common\model\FateCity;
use app\common\model\Goods;
use app\common\model\Map as MapModel;
use app\common\model\Map as MapRecode;
use app\common\model\Recode;
use think\exception\DbException;

/**
 * @title ACG地图相关接口
 * @desc 查看文章详情<br/>按页码获取文章列表，每页十条<br/>
 * @url /api/v2/article
 * @version 2.0.0
 * Class Article
 * @package app\api\controller\v2
 */
class Map extends Auth
{

    protected $MapCollect;

    protected $Map;

    /**
     * ACG首页 TODO 数据库查询缓存优化
     * @title
     * @method GET
     * @desc
     * @return array
     * @throws ApiException
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if (!request()->isGet()) return show(config('code.error'), '未知操作', [], 403);

        $rid = input('get.rid/d', 0);

        if (!$rid) return show(config('code.error'), '档案不存在');

        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        if (empty($recode))
        {
            return show(config('code.error'), '档案不存在');
        }
        // 获取用户当前已解锁的命格线 string 12位
        $unlockInfo = (new MapRecode())->getRecodeUnlockLines($recode, true);
        $lines = $unlockInfo['lines'];
        $planets = $unlockInfo['planets'];

        $i = 0;
        foreach ($planets['planet1'] as $k => $d)
        {
            if ($i >= 11) continue;// 仅过滤需要绘制的11颗星的数据中，未解锁购买的

            if ($lines['data'][$i] == 0)
            {
                unset($planets['planet1'][$k]);
                unset($planets['planet2'][$k]);
            }
            $i++;
        }

        if ($this->is_apple_pay)
        {
            $acg_goods = $this->apple_goods['acg_goods'];
        } else
        {
            $acg_goods = (new Goods())->getGoodsForACG();
        }

        // 从配置文件中加载相关配置
        $config = config('map');
        $line_list = [];// 所有命格线商品

        foreach ($acg_goods as $ag)
        {

            if ($ag['id'] > 18) continue;// 只需要11条线的数据

            $discount = (float)$ag['discount'];// 折扣

            $price = $discount ? $ag['or_prize'] * $discount : $ag['now_prize'];// 计算实际价格

            //商品折扣活动
            $activeDiscount = active($ag['id']);
            if ($activeDiscount['discount'] && !$this->is_apple_pay)
            {
                $price *= $activeDiscount['discount'];
            }

            $is_unlock = $lines['data'][$ag['id'] - 7] == 1;


            $line_list[] = [
                'gid' => $ag['id'],
                'name' => $ag['name'],
                'price' => sprintf("%.2f", $price),
                'icon' => $config['lines_icon'][$ag['id']],
                'description' => $config['lines_title'][$ag['id']],
                'color' => $config['lines_color'][$ag['id']],
                'is_unlock' => $is_unlock,
                'pid' => $config['pid'][$ag['id']],
                'planet' => $config['planet'][$ag['id']],
                'point_title' => $config['point_title'][$ag['id']],
                'point_des' => $config['point_des'][$ag['id']],
            ];
        }
        $line_list = resort($line_list, 'is_unlock');// 布尔值进行排序，暂未发现问题????

        $advertising = [
            'is_open' => true,
            'content' => config('map.advertising')['content'],
        ];

        $fate_city = [];
        // 计算命运之城数据
        if ($lines['data'][11] == 1)
        {
            $info = [
                'uid' => (int)$this->user['id'],
                'rid' => $rid,// 档案id
                'sex' => $recode['type'],// 档案性别
                'isself' => $recode['isself'],
                'longitude' => ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'],// 用户出生地经度
                'latitude' => ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'],// 用户出生地纬度
                'time' => strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute'])
                    - ($recode['timezone'] + $recode['is_summer']) * 3600,// 用户出生时间
            ];
            //0=>最新逻辑，无需更新，1=》逻辑需要更新，2=》逻辑计算中
            if ($lines['status'] != 2)
            {
                $fate_city = (new FateCity())->getUserFateCitys($info);
            }

//            $advertising['is_open'] = false;// 判断商品全部解锁后就关闭喇叭
        }

        if ($advertising['is_open'] === true && ($lines['data'] == '111111111111' || !config('map.advertising')['is_open'])) $advertising['is_open'] = false;// 后台控制喇叭关闭

        $result = [
            'lines_list' => $line_list,
            'planet1' => $planets['planet1'],
            'planet2' => $planets['planet2'],
            'fate_city' => $fate_city,
            'advertising' => (object)$advertising,
            'help_url' => config('map.help_url'),
            'is_alert' => false // TODO 弹窗信息未做
        ];
        return show(config('code.success'), '加载成功', $result);
    }


    /**
     * ACG地点详情
     * @return \think\response\Json
     * @throws ApiException
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read()
    {
        if (!request()->isGet()) return show(config('code.error'), '未知操作', [], 403);

        $type = input('get.type');// 地点类型

        $rid = input('get.rid');// 档案id

        if (!$rid) return show(config('code.error'), '档案不存在');

        $current_longitude = input('get.current_longitude');// 所在位置经纬度

        $current_latitude = input('get.current_latitude');// 所在位置经纬度

        $point_longitude = input('get.point_longitude');// 选择点的经纬度

        $point_latitude = input('get.point_latitude');// 选择点的经纬度

        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);

        $timestamp = strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute']);

        $timestamp -= ($recode['timezone'] + $recode['is_summer']) * 3600;

        $longitude = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];

        $latitude = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];

        $info = [
            'type' => $type,// 1=>普通地点，2=>命运之地
            'rid' => $rid,// 档案id
            'current_longitude' => $current_longitude,// 当前所在位置经度
            'current_latitude' => $current_latitude,// 当前所在位置纬度
            'point_longitude' => $point_longitude,// 选择的点的经度
            'point_latitude' => $point_latitude,// 选择的点的纬度
            'longitude' => $longitude,// 用户出生地经度
            'latitude' => $latitude,// 用户出生地纬度
            'time' => $timestamp,// 用户出生时间
            'sex' => $recode['type'],// 档案性别
            'isself' => $recode['isself'],// 当前档案是否为自己，检查是否有赠送记录，计算命格线对地点的影响
            'uid' => $this->user['id'],// 用户id
        ];

        $validate = validate('Map');

        if (!$validate->scene('read')->check($info)) return show(config('code.error'), (string)$validate->getError());
        // 获取选中地点分值
        $array = (new Acg())->getRecommendedInfo($info);
        // 获取选中地点收藏状态
        $collect_status = (new MapModel())->checkCollectStatus(['latitude' => $point_latitude, 'longitude' => $point_longitude, 'uid' => $this->user['id'], 'rid' => $rid]);

        $array['is_collect'] = $collect_status['is_collect'];
        $array['collect_id'] = $collect_status['collect_id'];

        if ($type == 2) $array['type'] = true;
        return show(config('code.success'), '加载成功', $array);
    }

    /**
     * 命格线列表
     * @throws ApiException
     */
    public function lines_list()
    {
        if (!request()->isGet()) return show(config('code.error'), '未知操作', [], 403);

        $rid = input('get.rid');

        $info = ['rid' => $rid];

        $validate = validate('Map');

        if (!$validate->scene('lines_list')->check($info)) return show(config('code.error'), (string)$validate->getError());

        $GoodsModel = new Goods();

        // 获取幸运之城商品信息
        if ($this->is_apple_pay)
        {
            $goods = $this->apple_goods['acg_goods'];
        } else
        {
            $goods = $GoodsModel->getGoodsForACG();
        }

        if ($goods === false)
        {
            return show(config('code.success'), $GoodsModel->getError());
        }
        $lines = [];
        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        // 获取用户当前已解锁的命格线 string 12位
        $unlockInfo = (new MapRecode())->getRecodeUnlockLines($recode);
        $unlock_lines = $unlockInfo['lines'];

        $activeDiscount['discount'] = 0;
        $array ['description'] = '';
        $pack_price = 99;
        foreach ($goods as $k => $v)
        {
            if ($v['id'] == 19)
            {
                $pack_price = $v['now_prize'];
            }

            if ($v['id'] > 18) continue;// 只需要11条线的数据

            $activeDiscount = active($v['id']);
            if ($activeDiscount['discount'] && !$this->is_apple_pay)
            {
                $price_temp = (string)($v['now_prize'] * $activeDiscount['discount'] * 100);
                $v['now_prize'] = (int)$price_temp / 100;
                $array ['description'] = $activeDiscount['discount'] . '折优惠';
            }

            if ($this->is_apple_pay)
            {
                $line = [
                    'name' => $v['name'],
                    'or_price' => (string)($v['or_prize']),
                    'now_price' => (string)($v['now_prize']),
                    'is_unlock' => false,
                    'gid' => $v['id']
                ];
            } else
            {
                $line = [
                    'name' => $v['name'],
                    'or_price' => sprintf("%.2f", $v['or_prize']),
                    'now_price' => sprintf("%.2f", $v['now_prize']),
                    'is_unlock' => false,
                    'gid' => $v['id']
                ];
            }
            if ($unlock_lines['data'][$v['id'] - 7] == 1 || in_array($this->user['id'], config('map.vip_uid')) || in_array($v['id'], [14, 15])) $line['is_unlock'] = true;

            $lines[] = $line;
        }
        // 将解锁的命格线重新排序
        $a = $b = [];
        foreach ($lines as $k => $v)
        {
            if ($v['is_unlock'])
            {
                $a[] = $v;
            } else
            {
                $b[] = $v;
            }
        }
        $lines = array_merge($a, $b);

        $array['lines'] = $lines;

        if ($activeDiscount['discount'] && !$this->is_apple_pay)
        {
            $price_temp = (string)($pack_price * $activeDiscount['discount'] * 100);
            $array['pack_price'] = (string)((int)$price_temp / 100);
        } else
        {
            $array['pack_price'] = (string)$pack_price;
        }
        return show(config('code.success'), '加载成功', $array);
    }
}
